package com.jsoft.interceptor;

import com.fasterxml.jackson.core.type.TypeReference;
import com.jsoft.configuration.CustomObjectMapper;
import com.jsoft.constant.Constants;
import com.jsoft.core.RedisTemplate;
import com.jsoft.entity.LoginUser;
import org.springframework.http.ResponseEntity;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;

/*
 * 登录校验拦截器
 * 判断每次请求是否带有Authorization
 * 如果携带，和redis中存放的进行比对
 * 如果匹配则放行，不匹配则拦截*/
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private CustomObjectMapper objectMapper;


    /**
     * 登录拦截器
     *
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        ResponseEntity<String> res = ResponseEntity.status(401).body("Bad Credentials");
        String token = request.getHeader(Constants.HEADER_AUTHORIZATION);
        String username = request.getHeader((Constants.HEADER_USERNAME));
        String tokenKey = Constants.TOKEN_PREFIX + username + ":" + token;
        //如果token空返回，说明未登录
        if (Objects.isNull(token)) {
            response.setStatus(401);
            response.getWriter().write(objectMapper.writeValueAsString(res));
            return false;
        }
        //如果不为空，拼上前后缀上redis里去找
        LoginUser loginUser = redisTemplate.getObject(tokenKey, new TypeReference<LoginUser>() {
        });
        if (Objects.isNull(loginUser)) {
            response.setStatus(401);
            response.getWriter().write(objectMapper.writeValueAsString(res));
            return false;
        }
        //登录校验通过，每次操作增加token的时间
        redisTemplate.expire(tokenKey, Constants.TOKEN_TIME);
        return true;
    }

}
